/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package th.stripes.action;

import able.stripes.JSP;
import com.google.inject.Inject;
import com.oas.thit._this.hajj.xsd.HajjResponseBody;
import com.oas.thit._this.offer.queryaccept.xsd.OfferQueryAcceptResponseBody;
import com.oas.thit._this.offer.subsidy.xsd.SubsidyDeclineResponseBody;
import com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponseBody;
import com.oas.thit._this.xsd.THISBaseDataElementBody;
import com.oas.thit.hajj.hjcheck.xsd.HjCheckRequestBody;
import com.oas.thit.hajj.hjcheck.xsd.HjCheckResponseBody;
import com.oas.thit.xmlmessage.xsd.Header;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBElement;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.HttpCache;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.action.Wizard;
import net.sourceforge.stripes.controller.LifecycleStage;
import org.apache.log4j.Logger;
import th.config.ableContextListener;
import th.dao.KodBandarDAO;
import th.dao.KodHubunganDAO;
import th.dao.KodJantinaDAO;
import th.dao.KodKahwinDAO;
import th.dao.KodNegeriDAO;
import th.dao.KodPekerjaanDAO;
import th.dao.KodSektorPekerjaanDAO;
import th.dao.KodStatusDAO;
import th.dao.KodStatusHajiDAO;
import th.dao.KodTahapPengajianDAO;
import th.dao.KodUrusanDAO;
import th.dao.KodWarganegaraDAO;
import th.dao.PoskodDAO;
import th.dao.PusatKosDAO;
import th.manager.HajjManager;
import th.manager.ResponseManager;
import th.manager.SejarahTransaksiManager;
import th.model.Deposit;
import th.model.Haji;
import th.model.InfoAudit;
import th.model.KodHubungan;
import th.model.KodStatusHaji;
import th.model.Kumpulan;
import th.model.Pengguna;
import th.model.PermohonanMaklumat;
import th.model.PermohonanMaklumatKumpulan;
import th.model.PermohonanMaklumatWaris;
import th.model.PilihanDestinasi;
import th.model.Poskod;
import th.model.SejarahTransaksi;
import th.model.SuratTawaran;
import th.model.THISutil;
import th.stripes.BaseActionBean;
import th.stripes.Configuration;
import th.stripes.config.AuthRequired;
import th.stripes.util.AccCheckUtil;
import th.stripes.util.DateFormatDetector;
import th.stripes.util.ListUtil;
import th.stripes.webservice.WebServiceUtil;


/**
 *
 * @author MSI
 */
@HttpCache(allow = false)
@Wizard(startEvents = "HajjSubD_Step1")
@UrlBinding("/haji/subsidyDecline")
public class HajiSubsidyDeclineActionBean extends BaseActionBean {
    
    private Pengguna pengguna;
    private Haji haji;
    private Kumpulan kumpulan;
    private Deposit deposit;
    
    private static String SUCCESSFUL = "0000";
    private static String ACCEPTED = "6000";
    private static String DECLINED = "6301";
    private static String CLOSED = "6300";    
    private static String SYSTEM_ERROR = "9999";   
    private static String INVALID_ACC_IC = "9000"; 
    private static String NO_HAJJ_OFR_RECORD = "7000";
    private static String NO_FLIGHT_SCH_RECORD = "7000";
    private static String ACCOUNT_ALREADY_REGISTRED = "7000";
    private static String UNSUCCESSFULL = "1000";
    
    @Inject HajjManager hajjManager;    
    @Inject private KodUrusanDAO kodUrusanDAO;
    @Inject private KodNegeriDAO kodNegeriDAO;
    @Inject private PoskodDAO poskodDAO;
    @Inject private KodKahwinDAO kodKahwinDAO;
    @Inject private KodWarganegaraDAO kodWarganegaraDAO;
    @Inject private KodTahapPengajianDAO kodTahapPengajianDAO;
    @Inject private KodSektorPekerjaanDAO kodSektorPekerjaanDAO;
    @Inject private KodPekerjaanDAO kodPekerjaanDAO;
    @Inject private KodHubunganDAO kodHubunganDAO;
    @Inject private KodStatusDAO kodStatusDAO;
    @Inject private KodStatusHajiDAO kodStatusHajiDAO;
    @Inject private PusatKosDAO pusatKosDAO;
    @Inject private KodBandarDAO kodBandarDAO;
    @Inject private ListUtil listUtil;
    @Inject private WebServiceUtil webUtil;
    @Inject private ResponseManager responseManager;
    @Inject private Configuration conf;
    @Inject private SejarahTransaksiManager sejarahTransaksiManager;
    @Inject private KodJantinaDAO kodJantinaDAO;
    
    private static Logger LOG = Logger.getLogger(DepositActionBean.class);
    private String KOD_URUSAN_JAWAB = "02";
    private String HAJJ_OFFR_ENQ_MSG_ID = "TPHJACCPWD01";
    private String HEADER_ID_ENQ = "THSHOQR";
    private String HAJJ_SUBSIDY_DEC_MSG_ID = "TPHJACCPWD06";
    private String HEADER_ID_DEC = "THSHSDL";
    private String HAJ_ENQ_MSG_ID = "TPHOFRCKWD01";
    private String HEADER_ID_HAJ_OFFER_CHECK = "THSHOCK";
    private static String HAJ_CHK_MSG_ID = "TPHAJCHKWD01";    
    private static String HEADER_ID_HAJ_REGISTRATION_CHECK = "THSHCHK";
    private static String PROFILE_ENQ_MSG_ID = "TPDPPROFWD01";
    private static String HEADER_ID_PROFILE_ENQUIRY = "THSDPQR";
    
    
    @DefaultHandler
    public Resolution showMainForm() {
        return new JSP("haji/main_haji.jsp");
    }  
    
    @Before(stages={LifecycleStage.BindingAndValidation})
    public void rehydrate() {
        pengguna = getContext().getCurrentUser();        
    }
    
   //-+-+-+-+-+-+-+-+-+-+-+-+-+-TOLAK TANGGUNGAN HAJI-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+// 
    @AuthRequired
    @HandlesEvent("HajjSubD_Step1")
    public Resolution showTolakTanggunganHajiMain()
     {

        haji=new Haji();
        pengguna = getContext().getCurrentUser();
        if (pengguna != null) {          
            haji.setNoKp(pengguna.getNoKp());
        }
        InfoAudit ia = new InfoAudit();
        ia.setDimasukOleh(pengguna);
        ia.setTarikhMasuk(new Date());  
         return new JSP("haji/jawabtawaran/tolak_tanggungan_haji_main.jsp");
     }
     
    @HandlesEvent("HajjSubD_Step2")
     public Resolution showTolakTanggunganHaji()
     {
        String responseCode = ""; 
        
        try {
            deposit = getProfileDeposit(haji.getNoAkaun(), haji.getNoKp());
        } catch (ParseException ex) {
            java.util.logging.Logger.getLogger(HajiActionBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        if (deposit != null) {
            
            AccCheckUtil checking = ableContextListener.newInstance(AccCheckUtil.class);
            deposit.setNoKpDari(haji.getNoKp());
            deposit.setNoAkaunDari(haji.getNoAkaun());
            boolean check = checking.checkAcc(deposit, pengguna);

            if (!check) {
                addSimpleError("" + responseManager.getResponseMessage("9000", PROFILE_ENQ_MSG_ID));
                return new JSP("deposit/msg.jsp");
            }
        } else {
            addSimpleError("" + responseManager.getResponseMessage("9000", PROFILE_ENQ_MSG_ID));
                return new JSP("deposit/msg.jsp");
        }
        
        try { // Call Web Service Operation
            com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
            com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap12Endpoint();
            // TODO initialize WS operation arguments here
            com.oas.thit._this.xsd.THISRequest req = new com.oas.thit._this.xsd.THISRequest();            
            
            com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();          
            com.oas.thit.xmlmessage.xsd.ObjectFactory objHeader = new com.oas.thit.xmlmessage.xsd.ObjectFactory();
            Header reqHead = objHeader.createHeader();
            reqHead.setMsgId( objHeader.createHeaderMsgId(HAJ_ENQ_MSG_ID));
            reqHead.setResponseCode( objHeader.createHeaderResponseCode(SUCCESSFUL) );
            
            reqHead.setTxid(objHeader.createHeaderTxid( webUtil.getHeaderID(HAJ_ENQ_MSG_ID, HEADER_ID_HAJ_OFFER_CHECK) ));
            
            JAXBElement<Header> jReqHead = objHeader.createEventHeader(reqHead);
            req.setHeader(jReqHead);            
            
            THISBaseDataElementBody reqBody = objFactory.createTHISBaseDataElementBody();
            reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(haji.getNoAkaun()));
            reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(haji.getNoKp()));
            
            JAXBElement<THISBaseDataElementBody> jReqBody =  objFactory.createTHISRequestBody(reqBody);
            req.setBody(jReqBody);  
            
            com.oas.thit._this.hajj.xsd.HajjResponse result = port.hajjCheckOffer(req);
            
            Header header = result.getHeader().getValue();
            responseCode = header.getResponseCode().getValue();
            
            //if (responseCode.equals(SUCCESSFUL) || responseCode.equals(ACCEPTED) || responseCode.equals(DECLINED) || responseCode.equals(CLOSED)) {
            if (responseCode.equals(SUCCESSFUL) || responseCode.equals(ACCEPTED) || responseCode.equals(CLOSED)) {
                HajjResponseBody resp = result.getBody().getValue();
                
                haji.setNama(resp.getTHName().getValue());
                haji.setNoAkaun(resp.getTHAcct().getValue());
                haji.setNoKp(resp.getTHICNo().getValue());
                haji.setTahunTawaran(resp.getTHYear().getValue().trim());
                haji.setTahunTawaranHijrah(resp.getTHYearI().getValue().trim());
                
                setHaji(haji);
                return new JSP("haji/jawabtawaran/tolak_tanggungan_haji.jsp");
            } else if (responseCode.equals(DECLINED)) {
                addSimpleError("TUAN / PUAN SUDAH MENOLAK TAWARAN");
            } else {
            addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_ENQ_MSG_ID));   
            }
        } catch (Exception ex) {
            LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJ_ENQ_MSG_ID)); 
        }
        return new JSP("haji/msg.jsp");
     }  
          
     
     
    @HandlesEvent("HajjSubD_Step3")
    public Resolution showTolakTanggunganHajiCetak()
    {
        String responseCode = "";
        DateFormat d = new SimpleDateFormat("yyyyMMdd");
        SejarahTransaksi sejarahTransaksi = new SejarahTransaksi();
        
            try { // Call Web Service Operation
                com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
                com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
                // TODO initialize WS operation arguments here
                com.oas.thit._this.xsd.THISRequest req = new com.oas.thit._this.xsd.THISRequest();
                com.oas.thit._this.xsd.ObjectFactory objFactory = new com.oas.thit._this.xsd.ObjectFactory();          
                com.oas.thit.xmlmessage.xsd.ObjectFactory objHeader = new com.oas.thit.xmlmessage.xsd.ObjectFactory();
                Header reqHead = objHeader.createHeader();
                reqHead.setMsgId( objHeader.createHeaderMsgId(HAJJ_SUBSIDY_DEC_MSG_ID));
                reqHead.setResponseCode( objHeader.createHeaderResponseCode(SUCCESSFUL) );

                reqHead.setTxid(objHeader.createHeaderTxid( webUtil.getHeaderID(HAJJ_SUBSIDY_DEC_MSG_ID, HEADER_ID_DEC) ));

                JAXBElement<Header> jReqHead = objHeader.createEventHeader(reqHead);
                req.setHeader(jReqHead);            

                THISBaseDataElementBody reqBody = objFactory.createTHISBaseDataElementBody();
                reqBody.setTHAcct(objFactory.createTHISBaseDataElementBodyTHAcct(haji.getNoAkaun()));
                reqBody.setTHICNo(objFactory.createTHISBaseDataElementBodyTHICNo(haji.getNoKp()));

                JAXBElement<THISBaseDataElementBody> jReqBody =  objFactory.createTHISRequestBody(reqBody);
                req.setBody(jReqBody); 
                
                
                // TODO process result here
                com.oas.thit._this.offer.subsidy.xsd.SubsidyDeclineResponse result = port.hajjsubsidyDecline(req);
                System.out.println("Result = "+result);
                Header header = result.getHeader().getValue();
                responseCode = header.getResponseCode().getValue();
                sejarahTransaksi.setPengguna(pengguna);
                sejarahTransaksi.setTrhMasuk(new Date());
                sejarahTransaksi.setUrusan(kodUrusanDAO.findById(HAJJ_SUBSIDY_DEC_MSG_ID));
                sejarahTransaksi.setIdSessi(getContext().getRequest().getSession().getId());
                sejarahTransaksi.setStatus(kodStatusDAO.findById(responseCode));
                sejarahTransaksi.setNilaiDalaman1(header.getTxid().getValue().trim());
                if (responseCode.equals(SUCCESSFUL)) {
                    SubsidyDeclineResponseBody resp = result.getBody().getValue();

                    haji.setNoAkaun(resp.getTHAcct().getValue().trim());
                    haji.setNoKp(resp.getTHICNo().getValue().trim());
                    haji.setNama(resp.getTHName().getValue().trim());
                    haji.setNoReg(resp.getTHRegNo().getValue().trim());
                    haji.setTahunTawaran(resp.getTHYear().getValue().trim());
                    haji.setTahunTawaranHijrah(resp.getTHYearI().getValue().trim());
                    haji.setTarikhTolakTanggunganHaji(d.parse(resp.getDeclineDate().getValue().trim()));
                    sejarahTransaksiManager.saveSejarahTransaksi(sejarahTransaksi);
                    getContext().getRequest().getSession().setAttribute("haji", haji); 
                    return new JSP("haji/jawabtawaran/tolak_tanggungan_haji_detail.jsp");                      
                }
                addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJJ_SUBSIDY_DEC_MSG_ID));
            } catch (Exception ex) {
                LOG.error(ex);
            responseCode = SYSTEM_ERROR;
            addSimpleError("" + responseManager.getResponseMessage(responseCode, HAJJ_SUBSIDY_DEC_MSG_ID));        
            }          
        return new JSP("haji/msg.jsp");
    }
  

      /**
     * Get profile from deposit
     * @param noAkaun
     * @param noKP
     * @return 
     * 
     */
    public Deposit getProfileDeposit(String noAkaun, String noKP) throws ParseException {
       
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        String responseCode = "";
        //Deposit deposit = null;
        
        com.oas.thit._this.services.THISServices service = new com.oas.thit._this.services.THISServices();
        com.oas.thit._this.services.THISServicesPortType port = service.getTHISServicesHttpSoap11Endpoint();
        com.oas.thit._this.xsd.THISRequest reqDeposit = new com.oas.thit._this.xsd.THISRequest();
        com.oas.thit._this.xsd.ObjectFactory objFactoryDeposit = new com.oas.thit._this.xsd.ObjectFactory();
        reqDeposit.setHeader( webUtil.createHeader(PROFILE_ENQ_MSG_ID, HEADER_ID_PROFILE_ENQUIRY) );
        THISBaseDataElementBody reqBodyDeposit = objFactoryDeposit.createTHISBaseDataElementBody();
        
        reqBodyDeposit.setTHAcct(objFactoryDeposit.createTHISBaseDataElementBodyTHAcct(noAkaun));
        reqBodyDeposit.setTHICNo(objFactoryDeposit.createTHISBaseDataElementBodyTHICNo(noKP));

        JAXBElement<THISBaseDataElementBody> jReqBodyDeposit =  objFactoryDeposit.createTHISRequestBody(reqBodyDeposit);
        reqDeposit.setBody(jReqBodyDeposit);
        
         /*
          * Query for deposit : profile
          */
            com.oas.thit._this.profile.depositor.xsd.DepositorProfileResponse resultDeposit = port.depositorProfileQuery(reqDeposit);
            Header headerDeposit = resultDeposit.getHeader().getValue();
            responseCode = headerDeposit.getResponseCode().getValue();
            if (responseCode.equals(SUCCESSFUL)) {
                 DepositorProfileResponseBody respDeposit = resultDeposit.getBody().getValue();
                 if (respDeposit != null) { 
                    deposit = new Deposit();
                    deposit.setAlamat1(respDeposit.getTHAddress1().getValue());
                    deposit.setAlamat2(respDeposit.getTHAddress2().getValue());
                    deposit.setAlamat3(respDeposit.getTHAddress3().getValue());
                    deposit.setBangsa(respDeposit.getTHEthnic().getValue());
                    deposit.setEmail(respDeposit.getTHemail().getValue());
                    deposit.setNoAkaun(respDeposit.getTHAcct().getValue().trim());
                    deposit.setNoBuku(respDeposit.getTHPassbookNo().getValue());
                    deposit.setNoKp(respDeposit.getTHICNo().getValue().trim());
                    deposit.setNoTel1(respDeposit.getTHPhoneHome().getValue());
                    deposit.setNoTel2(respDeposit.getTHPhoneMobile().getValue());
                    deposit.setNoTel3(respDeposit.getTHPhoneOffice().getValue());
                    deposit.setPoskod(respDeposit.getTHPoskod().getValue());
                    deposit.setNama(respDeposit.getTHName().getValue());
                    
                    if (respDeposit.getTHGender() != null) {
                        deposit.setJantina(kodJantinaDAO.findById(respDeposit.getTHGender().getValue().trim()));
                    }
                    if  (respDeposit.getTHMarital() != null) {
                        deposit.setKahwin(kodKahwinDAO.findById(respDeposit.getTHMarital().getValue().trim()));
                    }
                   
                    if (respDeposit.getTHState() != null) {
                        deposit.setNegeri(kodNegeriDAO.findById(respDeposit.getTHState().getValue().trim()));
                    }
                     if (respDeposit.getTHEmploy() != null) {
                        deposit.setPekerjaan(kodPekerjaanDAO.findById(respDeposit.getTHEmploy().getValue().trim()));
                    }
                    if (respDeposit.getTHNationality() != null) {
                        deposit.setWarganegara(kodWarganegaraDAO.findById(respDeposit.getTHNationality().getValue().trim()));
                    }
                    
                    /*
                     * Set date
                     */
                    String df = new DateFormatDetector().getDateFormat(respDeposit.getTHDOB().getValue());
                    sdf = new SimpleDateFormat(df);
                    deposit.setTarikhLahir(sdf.parse(respDeposit.getTHDOB().getValue()));
                    
                 }
            }
        return deposit;
    }
     
      public Pengguna getPengguna() {
        return pengguna;
    }

    public void setPengguna(Pengguna pengguna) {
        this.pengguna = pengguna;
    }

    public Haji getHaji() {
        return haji;
    }

    public void setHaji(Haji haji) {
        this.haji = haji;
    }

    public Kumpulan getKumpulan() {
        return kumpulan;
    }

    public void setKumpulan(Kumpulan kumpulan) {
        this.kumpulan = kumpulan;
    }
 
}
